package com.aerotechnic.dao;

import java.util.List;
import java.util.StringTokenizer;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.aerotechnic.dao.GenericDao;
import com.aerotechnic.models.BaseEntity;
import com.aerotechnic.util.CustomHibernateDaoSupport;

public abstract class BaseDao<E extends BaseEntity> extends
		CustomHibernateDaoSupport implements GenericDao<E> {
	private Class<E> type;
	private String currentGeniricClassName;

	public BaseDao() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		type = (Class<E>) pt.getActualTypeArguments()[0];
		currentGeniricClassName=getClassNameFromPackage();
	}

	public void save(E e) {  
		getHibernateTemplate().save(e);
	}

	public void delete(E e){
		getHibernateTemplate().delete(e);
	}

	public E findByID(Long id){
		return (E)getHibernateTemplate().find("from "+currentGeniricClassName+" where id="+id).get(0);
	}
	public List<E> findAll(){
		return (List<E>)getHibernateTemplate().find("from "+currentGeniricClassName);
	}

	public void update(E e){
		getHibernateTemplate().update(e);
	}

	private String getClassNameFromPackage(){
		StringTokenizer strTkn = new StringTokenizer(type.toString(),".");
		String temp="";
		while(strTkn.hasMoreElements()){
			temp=(String) strTkn.nextElement();
		}
		return temp;
	}

}
